package com.ls.lserp.modules.finance.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.SpringContextHolder;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.dbaccess.Entity.FinanceEntity;
import com.ls.lserp.dbaccess.Entity.OgnizationSettlementEntity;
import com.ls.lserp.modules.finance.entity.InitFinance;
import com.ls.lserp.modules.finance.service.InitFinanceService;
import com.ls.lserp.modules.material.entity.InventoryRequest;
import com.ls.lserp.modules.material.entity.MaterialOutInbound;
import com.ls.lserp.modules.material.service.MaterialInboundService;
import com.ls.lserp.modules.order.entity.BigcargoOrder;
import com.ls.lserp.modules.setting.entity.Ognization;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

/**
 * @ClassName: CustomerController
 * @Description: 
 * 
 * @author 刘晓彤
 * @date 2017年3月16日 
 *
 */


@Controller
@RequestMapping(value = "${adminPath}/init/finance/")
public class InitFinanceController extends BaseController {

	@Autowired
	private InitFinanceService initFinanceService;
	@Autowired
	Configuration freemarkerConfiguration;
	
	@ModelAttribute
	public OgnizationSettlementEntity get(@RequestParam(required = false) String id) {

		// 判断id是否为空
		if (StringUtils.isNotBlank(id)) {
			// 执行查询语句 查询基本信息
			return initFinanceService.get(Long.parseLong(id));
		} else {
			// 若为空，实例化
			return new OgnizationSettlementEntity();
		}
	}
	
	
	
	/**
	 * 进入一览画面
	 * 
	 * 
	 * @return
	 */
	@RequiresPermissions("init:finance:view")
	@RequestMapping(value = { "" })
	public String list(FinanceEntity financeEntity, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		//返回页面地址
		return "modules/finance/initFinance";

	}
	
	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param initFinance
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws Exception
	 */
	@RequiresPermissions("init:finance:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(OgnizationSettlementEntity settlementEntity, HttpServletRequest request, HttpServletResponse response,
			Model model) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "initFinance");
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		// 机构名称
		searchParam.append("&ognization.ognizationName=");
		searchParam.append(settlementEntity.getOgnization().getOgnizationName());
		// 机构类型
		searchParam.append("&ognization.ognizationType=");
		searchParam.append(settlementEntity.getOgnization().getOgnizationType());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		
		// 查询一览页面数据
		Page<OgnizationSettlementEntity> page = initFinanceService.findList(new Page<OgnizationSettlementEntity>(request, response),settlementEntity);
		// 读取系统路径
		String strUri = request.getContextPath() + Global.getAdminPath();
		// 读取文件生成字符串
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("initFinances", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		map.put("springMacroRequestContext", new RequestContext (request));
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("initFinance.ftl"), map);
		listMap.put("initFinance", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}
	
	
	/**
	 * 
	 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流
	 * 
	 * @param filePath
	 * @return html
	 */
	public String readTxtFile(String filePath) {
		String strHtml = "";
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			// 判断文件是否存在
			if (file.isFile()) {
				InputStreamReader read = new InputStreamReader(
						// 考虑到编码格式
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lingText = null;
				while ((lingText = bufferedReader.readLine()) != null) {
					strHtml += lingText;
				}
				read.close();
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strHtml;
	}
	
	/**
	 * 创建编辑保存仓库信息
	 * 
	 * @return
	 * @throws ParseException
	 * @throws ResourceException
	 */
	@RequiresPermissions("init:finance:edit")
	@RequestMapping(value = "save")
	@ResponseBody
	public String save(OgnizationSettlementEntity settlementEntity, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ResourceException {
		
		// 判断id是否为null （判断新建或修改）
		if(settlementEntity.getId()!=null){
			// 编辑数据
			// 判断数据是否删除
			OgnizationSettlementEntity settlementEntityNew = get(settlementEntity.getId().toString());
			// 判断数据是否删除
            if(settlementEntityNew==null || BaseEntity.DEL_FLAG_DELETE.equals(settlementEntityNew.getDeleteFlag())){
            	// 返回提示信息
            	return renderString(response,AjaxDone.error(SystemMessageUtils.getMessageName("System_error_please_contact_your_administrator")));
            }
			
            // 排他处理
		    if(settlementEntity.getVersion()==get(settlementEntity.getId().toString()).getVersion()){
		    	
		    	// 版本号加1
		    	settlementEntity.setVersion(settlementEntity.getVersion()+1);
		    }else{
		    	
		    	// 返回提示信息
		    	return renderString(response,AjaxDone.error(SystemMessageUtils.getMessageName("System_error_please_contact_your_administrator")));
		    }
		}
			
			
		    // 保存数据
			try {
				initFinanceService.saveInitFinance(settlementEntity);
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
				return renderString(response,AjaxDone.error(SystemMessageUtils.getMessageName("System_error_please_contact_your_administrator")));
			}
			
			// 保存成功返回提示信息
			return renderString(response, AjaxDone.ok(SystemMessageUtils.getMessageName( "settlement_save_success")));
			
			
	}
	
	/**
	 * 查存
	 * 
	 * @return
	 * @throws ParseException
	 * @throws ResourceException
	 */
	@RequiresPermissions("init:finance:edit")
	@RequestMapping(value = "checkExsit")
	@ResponseBody
	public String checkExsit(OgnizationSettlementEntity settlementEntity, HttpServletRequest request, HttpServletResponse response,
			Model model) throws ResourceException {
			OgnizationSettlementEntity ostEntity = initFinanceService.getByOgnizationId(settlementEntity.getOgnizationId());
			if (ostEntity == null) {
				return renderString(response,"true");
			}else {
				return renderString(response,"false");
			}
	}
	/**
	    * 进入创建页面
	    * @param initFinance
	    * @param model
	    * @return
	    */
	   @RequiresPermissions("init:finance:view")
	   @RequestMapping(value = "createInit")
	   public String createInit(OgnizationSettlementEntity settlementEntity, Model model) {
		   //获取机构集
		   List<Ognization> ognizationList = initFinanceService.findOgnizationList();
		   settlementEntity.preInsert();
	       // 将查询结果赋值mvc model层返回jsp页面
	       model.addAttribute("settlementEntity", settlementEntity);
	       model.addAttribute("ognizationList", ognizationList);
	       
	       // 返回页面地址
	       return "modules/finance/initFinanceCreate";
	   }
	   /**
	    * 进入查看页面
	    * @param initFinance
	    * @param model
	    * @return
	    */
	   @RequiresPermissions("init:finance:view")
	   @RequestMapping(value = "viewInit")
	   public String viewInit(OgnizationSettlementEntity settlementEntity, Model model) {
		   
	       // 将查询结果赋值mvc model层返回jsp页面
	       model.addAttribute("settlementEntity", settlementEntity);
	       
	       // 返回页面地址
	       return "modules/finance/initFinanceShow";
	   }
	/**
	 * 机构联动
	 * 
	 * @return
	 */
	@RequiresPermissions("init:finance:view")
	@RequestMapping(value = {"ognizatianFun"})
	public String ognizatianFun(FinanceEntity financeEntity,Model model){
		 model.addAttribute("financeEntity", initFinanceService.getOgnizationInfo(financeEntity));
		 return "modules/finance/initFinanceCreate";
	}
	
}
